<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 左侧显示记录数 -->
        <template v-slot:before>
          <span>{{ page.total }}条记录</span>
        </template>
        <!-- 右侧显示按钮 excel导入 excel导出 新增员工-->
        <template v-slot:after>
          <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">excel导出</el-button>
          <el-button :disabled="!checkPermission('POINT-USER-ADD')" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card>
        <!-- 表格组件 -->
        <el-table v-loading="loading" :data="employeelist" border>
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center" width="150">
            <template v-slot="{row}">
              <img
                v-imagerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <!-- 作用域插槽+过滤器 -->
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{row}">
              <el-switch :value="row.enableState===1" />
              <!-- {{ row.enableState===1?'可用':'不可用' }} -->
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="page.total" :current-page="page.page" :page-size="page.size" layout="prev,pager,next" @current-change="pageChange" />
        </el-row>
      </el-card>
      <!-- 新增员工对话框 -->
      <!-- sync修饰符 子组件改变父组件数据的语法糖-->
      <add-employee :show-dialog="showDialog" @addsuccess="addsuccess" @cancelSuccess="cancelSuccess" />
      <!-- 图片二维码的预览对话框 -->
      <el-dialog title="图片二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 新增角色分配 -->
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees' // 引入员工的枚举对象
import addEmployee from './components/add-employee' // 引用子组件可用相对路径
import assignRole from './components/assign-role.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      employeelist: [],
      // 显示遮罩层
      loading: false,
      // 新增员工对话框的显示与隐藏
      showDialog: false,
      // 控制二维码对话框的显示与隐藏
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工数据列表
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      console.log(rows)
      // rows.forEach(item => { item.formOfEmployment = item.formOfEmployment === 1 ? '正式' : '非正式' })
      console.log(rows)
      this.employeelist = rows
      this.page.total = total
      console.log(total)
      this.loading = false
    },
    // 在页码切换时触发的事件默认拿到切换的页码数
    pageChange(newPage) {
      console.log(newPage)
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化员工雇佣状态
    formatEmployment(row, column, cellValue, index) {
      // 要去找1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    addsuccess(val) {
      this.getEmployeeList()
      this.showDialog = val
      this.$message.success('操作成功')
    },
    cancelSuccess(val) {
      this.showDialog = val
    },
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出excel
      // excel是引入文件的导出对象
      // 导出header
      // data从哪里来
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        console.log(data)
        export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工资料表',
          multiHeader,
          merges
          // 没有一个接口获取所有的数据
          // 读取员工的接口页码每页条数 100 1
        })
        // list是每一页的数据
        //   header: ['姓名', '工资'],
        //   data: [['张三', 3000], ['李四', 4000]],
        //   filename: '员工工资表',
        //   bookType: 'xlsx'
        // })
        // [{username:'张三',mobile:131252485}]=>[[]]
        // 要转化数据结构还要和表头的顺序对应上
        // 转出的标题是中文
      })
    },
    // 将表头数据和数据进行对应
    // [{}]=>[[]]
    formatJson(headers, rows) {
      return rows.map(item => {
        // ['手机号','姓名','入职日期']
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            console.log(item[headers[key]])
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            var res = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return res ? res.value : '未知'
          }
          return item[headers[key]]
        })
      })
      // var arr = []
      // rows.forEach(item => {
      //   var arr1 = []
      //   Object.keys(headers).forEach(key => {
      //     arr1.push(item[headers[key]])
      //     console.log(item[key])
      //     console.log(arr1)
      //   })
      //   arr.push(arr1)
      // })
      // console.log(arr)
      // return arr
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    showQrCode(url) {
      // url存在才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了我弹层会出现吗？弹层不会出现页面渲染是异步的
        // 可以等到上一次数据更新完毕, 页面渲染完毕后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url)// 将地址转化成为二维码
          // 如果二维码信息是地址就会跳转到该地址,如果不是地址就会显示该内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) {
      // 弹出层
      this.userId = id // props赋值 props赋值并且渲染是异步的
      await this.$refs.assignRole.getUserDetailById(id)// 调用子组件方法把当前id传过去 //异步方法
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
